var pageListUrl = rootPath + "s/sms/tpl/page/list";//分页查询
var detailUrl = rootPath + "s/sms/tpl/detail";//获取详情
var saveUrl = rootPath + "s/sms/tpl/save";//保存编辑
var delUrl = rootPath + "s/sms/tpl/del";//删除
var auditUrl = rootPath + "s/sms/tpl/audit";//提交模板审核
var reAuditUrl = rootPath + "s/sms/tpl/reaudit";//提交模板重新审核
var latestStatusUrl = rootPath + "s/sms/tpl/latest/status";//更新模板列表
var toEditPageUrl = rootPath + "s/sms/tpl/edit.cgi";


/**
 * 分页
 * @returns
 */
function queryList(){
	var results;
    $("#datagrid").datagrid({
//        url : pageListUrl,
        pagination:true,//分页控件
        width : 'auto',// 面板宽度，自动列宽 
        height : 'auto',// 面板高度，自动列高 
        nowrap : false,// :当true时，显示数据在同一行上。默认true。
        checkOnSelect: true,
        rownumbers: true,
        selectOnCheck: true,
        singleSelect:false,
        autoRowHeight:true,
        fitColumns: true,
        pageNo :0,
        pageSize :10,
        queryParams : getQueryParam(),
        loadFilter : function (rs) {
            if(rs.opStatus == "0"){
            	$("#pageNo").val(rs.data.pageNo);
            	$("#pageSize").val(rs.data.pageSize);
            	results = rs.data.results;
            	var data ={
            		"rows":	rs.data.results,
            		"total":rs.data.totalRecord
            	};
                return data;
            }
        },
        columns : [ [  {
            field:'_',
            checkbox:true,
            width:'5%'
        },{
            field : 'company',
            title : '签名',
            width : '8%',
            align : 'center'
        }, {
            field : 'code',
            title : '编码',
            width : '15%',
            align : 'center'
        }, {
            field : 'tplId',
            title : '云片模板ID',
            width : '7%',
            align : 'center'
        },  {
            field : 'content',
            title : '内容',
            width : '33%',
            align : 'center'
        },
        {
            field : '复制内容',
            title : '复制内容',
            width :'10%',
            align : 'center',
            formatter:function(data,row){
                 var b = '<button class="btn btn-default btn-xs" type="button" onclick="copyToClipboard(\''+row.content+'\')"><i class="glyphicon glyphicon-thumbs-up"></i> 点击复制</button>';
                return b;
            }
        }, 
        {
            field : 'createTime',
            title : '创建时间',
            align : 'center',
            width : '10%',
            formatter:function(rs){
                if(rs){
                	var date = new Date(rs)
                    return dateToString(date);
                }
            }
        }, {
            field : 'checkStatus',
            title : '审核状态',
            align : 'center',
            width : '5%',
            formatter : function (data,row){
            	var color = "";
            	var font = "";
            	if(data == "SUCCESS"){
            		color = "green";
            		font = "已通过";
            	}else  if(data == "CHECKING"){
            		color = "orange";
            		font = "审核中";
            	}else if(data == "FAIL"){
            		color = "red";
            		font = "审核不通过";
            	}else if(data == "RE_AUDIT"){
            		return '<button class="btn btn-default btn-xs" type="button" onclick="reAuditTpl(\''+row.smsTeplId+'\')"><i class="glyphicon glyphicon-hand-up"></i> 重新审核</button>';
            	}else {
            		return '<button class="btn btn-default btn-xs" type="button" onclick="auditTpl(\''+row.smsTeplId+'\')"><i class="glyphicon glyphicon-hand-up"></i> 未审核</button>';
            	}
            	return "<font color='"+color+"'>"+font+"</font>";
            }

        },
        {
            field : 'smsTeplId',
            title : '操作',
            width :'10%',
            align : 'center',
            formatter:function(data,row){
                var str = '<button class="btn btn-default btn-xs" type="button" onclick="toEditPage(\''+data+'\',\''+row.checkStatus+'\')"><i class="glyphicon glyphicon-pencil"></i> 修改</button>';
                return str;
            }
        }] ],
        onDblClickRow : function(index,row){
        }
    });
}

/**
 * 复制文本内容致剪贴板
 * @param text
 * @returns
 */
function copyToClipboard (text) {
	      if(text.indexOf('-') !== -1) {
	          let arr = text.split('-');
	          text = arr[0] + arr[1];
	      }
	     var textArea = document.createElement("textarea");
	       textArea.style.position = 'fixed';
	       textArea.style.top = '0';
	       textArea.style.left = '0';
	       textArea.style.width = '2em';
	       textArea.style.height = '2em';
	       textArea.style.padding = '0';
	       textArea.style.border = 'none';
	       textArea.style.outline = 'none';
	       textArea.style.boxShadow = 'none';
	       textArea.style.background = 'transparent';
	       textArea.value = text;
	       document.body.appendChild(textArea);
	       textArea.select();
	 
       try {
	         var successful = document.execCommand('copy');
	         var msg = successful ? '成功复制到剪贴板' : '该浏览器不支持点击复制到剪贴板';
	         showMsg(msg);
       } catch (err) {
	    	 showMsg('该浏览器不支持点击复制到剪贴板');
      }
	
       document.body.removeChild(textArea);
	 }
/**
 * 获取查询表单的参数
 * @returns
 */
function getQueryParam (){
	var html = $("#datagrid").html();
	if(html == ""){
		var pageSize;
		var pageSizeStr = $("#pageSize").val();
		if(pageSizeStr && pageSizeStr != ""){
			pageSize = parseInt(pageSizeStr);
		}
		var pageNo;
		var pageNoStr = $("#pageNo").val();
		if(pageNoStr && pageNoStr != ""){
			pageNo = parseInt(pageNoStr);
		}
	}else {
		
	}
	
	
	
	var beginTime = $("#beginTime").val();
	var endTime = $("#endTime").val();
	var company = $("#company").val();
	var code = $("#code").val();
	var content = $("#content").val();
	var tplId = $("#tplId").val();
	var checkStatus = $("#checkStatus").val();
    var param = {
    		"pageNo" : pageNo,
    		"pageSize" : pageSize,
    		"beginTime" : beginTime,
    		"endTime" : endTime,
    		"smsTemplateEntity.company" : company,
    		"smsTemplateEntity.code" : code,
    		"smsTemplateEntity.content" : content,
    		"smsTemplateEntity.tplId" : tplId,
    		"smsTemplateEntity.checkStatus" : checkStatus
    };
    return param;
};

/**
 * 提交模板审核
 * @returns
 */
function auditTpl(id){
	$.ajax({
        url : auditUrl,
        type : 'post',
        data :{"ids":id},
        async :false,
        success : function (res) {
       	 showMsg(res.msgDesc);
            if(res.opStatus == "0"){
           	 showMsg(res.msgDesc);
           	refreshGrid()
            }
        }
    });
}

/**
 * 刷新所有短信模板
 * @returns
 */
function latestStatus(){
	 $.ajax({
         url : latestStatusUrl,
         type : 'post',
         data :null,
         async :false,
         success : function (res) {
        	 showMsg(res.msgDesc);
             if(res.opStatus == "0"){
            	 showMsg(res.msgDesc);
            	refreshGrid()
             }
         }
     });
}

/**
 * 重新审核短信模板
 * @param id
 * @returns
 */
function reAuditTpl(id){
	 $.ajax({
         url : reAuditUrl,
         type : 'post',
         data :{'id' : id},
         success :function (res) {
		           showMsg(res.msgDesc);
		          refreshGrid()
             }
     });
}
/**
 * 前往编辑页面
 * @param id
 * @returns
 */
function toEditPage(id,checkStatus){
	if(id && id != ""){//修改
		$("#edit-modal").load(toEditPageUrl + "?id=" + id,{_: Math.random()},function () {
			 $.ajax({
		            url : detailUrl,
		            type : 'post',
		            data :{'id' : id},
		            success :function (res) {
			               if( res.opStatus == "0"){
			            	   $("#edit_company").val(res.data.company);
			            	   $("#edit_code").val(res.data.code);
			            	   $("#edit_content").val(res.data.content);
			            	   if(res.data.code && res.data.code != ""){
			            		   $("#edit_code").attr("readonly","readonly");
			            	   }
			               }else {
			            	   showMsg(res.msgDesc);
			               }
			               $('#editModalLabel').html("修改");
			               $('#editModal').modal('show');
			               if(checkStatus && checkStatus != "" && checkStatus != "undefined"){
			            	   showMsg("如果修改了短信模板的【内容】,哪怕只是一个标点符号，也要重新审核！");
			               }
		                }
		        });
		 
		        
		    });
	}else {//添加
		$("#edit-modal").load(toEditPageUrl,{_: Math.random()},function () {
			 $('#editModal').modal('show');
		});
	}
}

/**
 * 提交编辑页面表单
 * @returns
 */
function save(){
	var company = $("#edit_company").val();
	var code = $("#edit_code").val();
	var content = $("#edit_content").val();
	var id = $("#edit_id").val();
	param = {
		"company" : company,
		"code" : code,
		"content" : content,
		"smsTeplId" : id
	}
	$.ajax({
        url : saveUrl,
        type : 'post',
        data :param,
        success :function (res) {
        	if(res.opStatus == "0"){
        	 showTip(res.msgDesc,1000,function () {
                 $("#editModal").modal("hide");

                refreshGrid()
             });
        	}else {
              showMsg(res.msgDesc);
        	}
        }
    });
}

/**
 * 删除
 * @returns
 */
function del(){
	
	var rows = $("#datagrid").datagrid("getChecked");
    if(rows.length > 0){
        showConfirm("是否确认删除？",function () {
            var ids = [];
            for(var i in rows ){
                ids.push(rows[i].smsTeplId);
            }
            var idsStr = ids.join(",");
            $.ajax({
                url : delUrl,
                type : 'post',
                data :{"ids" :idsStr},
                success : function (res) {
                    if(res.opStatus == "0"){
                        showTip(res.msgDesc,1000,function () {
                        	refreshGrid();
                        });
                    }else {
                        showMsg(res.msgDesc);
                    }
                }
            })
        });
    }else {
        showMsg("请在需要删除的项目前面打上“勾勾”！");
    }
}
/**
 * 刷新分页列表
 * @returns
 */
function refreshGrid(){
	 $("#datagrid").datagrid("reload",getQueryParam());
}
$(document).ready(function () {
	$("#add_button").on("click",function(){
		toEditPage("");
	});
	$("#refresh_tpl_button").on("click",function () {
		latestStatus();
    });
	 $("#remove_button").on("click",function () {
	       del()
	    });
	 $("#search_button").on("click",function () {
	    	refreshGrid();
	    });
	queryList();//加载分页数据
	var rows = $("#datagrid").datagrid("getPager");
	$("#datagrid").datagrid({
			url:pageListUrl,
			onBeforeLoad:function(param){
            param.pageSize = param.rows;
            param.pageNo = param.page;
            param.rows = null;
            param.page = null;
         }
    }); 

	
	
	
});